import requests
import pymongo
import schedule
from config.configs import ALPHA_DB_HOST, ALPHA_DB_PORT
from tools.funciton import spuId_to_articleNumber, skuId_to_size, write_xlsx
import datetime
from time import sleep
from apscheduler.schedulers.background import BackgroundScheduler

alpha = pymongo.MongoClient(ALPHA_DB_HOST, ALPHA_DB_PORT).alpha
header = {'Content-Type': "application/json; charset=utf-8",
          'Authorization': "Bearer u-d8.RObKRBdLFPlwbhnY6Tv042m2B04BHiO004kO22FjG"}


def refresh_token():
    """刷新token"""
    url = 'https://open.feishu.cn/open-apis/authen/v1/oidc/access_token'


def search_code(code):
    """根据扫码枪识别的69码查询货号尺码"""
    articleNumber, size = [], []
    pipeline = [
        {
            '$match':
                {
                    'barcode': str(code)
                }
        },
        {
            '$lookup':
                {
                    'from': "spus",
                    'localField': "spuId",
                    'foreignField': "spuId",
                    'as': "result"
                }
        },
        {
            '$unwind':
                {
                    'path': "$result"
                }
        },
        {
            '$project':
                {
                    'articleNumber': "$result.articleNumber"
                }
        }
    ]

    for i in alpha.skus.find({'barcode': str(code)}):
        if 'properties' in i:
            size.append(i['properties'].split('"尺码":"')[1].split('"')[0])
            [articleNumber.append(i['articleNumber']) for i in alpha.skus.aggregate(pipeline)]
            return [articleNumber[0], size[0], code]
    else:
        return ['未查询到69码']


def search_codes(codes):
    """根据扫码枪识别的69码查询货号尺码"""
    articleNumber, size = [], []
    for code in codes:
        pipeline = [
            {
                '$match':
                    {
                        'barcode': str(code)
                    }
            },
            {
                '$lookup':
                    {
                        'from': "spus",
                        'localField': "spuId",
                        'foreignField': "spuId",
                        'as': "result"
                    }
            },
            {
                '$unwind':
                    {
                        'path': "$result"
                    }
            },
            {
                '$project':
                    {
                        'articleNumber': "$result.articleNumber"
                    }
            }
        ]
        result = alpha.skus.find_one({'barcode': str(code)})
        if None is not result:
            size.append([result['properties'].split('"尺码":"')[1].split('"')[0]])
            [articleNumber.append([i['articleNumber']]) for i in alpha.skus.aggregate(pipeline)]

        else:
            size.append(['无匹配尺码'])
            articleNumber.append(['无匹配货号'])
    return articleNumber, size


def cloud_excel_insert(value):
    """飞书云文档追加内容"""
    url = 'https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/JHqvshlN4hmjOxtbQP4c37Rpnsh/values_append'
    param = {
        "valueRange": {
            "range": "FURSZ9",
            "values": [
                value
            ]
        }
    }
    requests.post(url=url, headers=header, json=param)


def read_range_datas(spreadsheetToken, sheetId, start, end):
    """飞书云文档读取code"""
    li, dif = [], end - start + 1
    url = f'https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{spreadsheetToken}/values_batch_get'
    param = {
        "ranges": f"{sheetId}!C{start}:C{end}"
    }
    r = requests.get(url=url, headers=header, params=param)
    li.extend(r.json()['data']['valueRanges'][0]['values'])
    while [None] not in r.json()['data']['valueRanges'][0]['values']:
        start += dif
        end += dif
        param1 = {
            "ranges": f"{sheetId}!C{start}:C{end}"
        }
        r = requests.get(url=url, headers=header, params=param1)
        li.extend(r.json()['data']['valueRanges'][0]['values'])
    else:
        while [None] in li:
            li.remove([None])
        else:
            li1 = [str(i[0]) for i in li]
            return li1


def insert_range():
    """飞书指定位置插入数据"""
    url = f'https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/JHqvshlN4hmjOxtbQP4c37Rpnsh/values_batch_update'
    dif = len(read_range_datas('JHqvshlN4hmjOxtbQP4c37Rpnsh', 'FURSZ9', 2, 10))
    codes = read_range_datas('JHqvshlN4hmjOxtbQP4c37Rpnsh', 'FURSZ9', 2, 10)
    article, size = search_codes(codes)
    param = {
        "valueRanges": [
            {
                "range": f"FURSZ9!A2:A{dif + 1}",
                "values":
                    article
            },
            {
                "range": f"FURSZ9!B2:B{dif + 1}",
                "values":
                    size
            }
        ]
    }
    r = requests.post(url=url, headers=header, json=param)
    print(r.json())


# scheduler = BackgroundScheduler()
# scheduler.add_job(insert_range,'interval',seconds=10)
# scheduler.start()
# sleep(1000)
# scheduler.shutdown()

# req = requests.get(
#     url='https://open.feishu.cn/open-apis/authen/v1/authorize?app_id=cli_a4292e11213c500b&redirect_uri=https%3A%2F%2F127.0.0.1')
# print(req.text)
